package com.eternal.notification.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.facade.callback.NavCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eternal.base.concat.BluetoothEvent;
import com.eternal.base.concat.DeviceName;
import com.eternal.base.data.RepositoryInjection;
import com.eternal.base.global.ActivityEvent;
import com.eternal.base.global.BluetoothKey;
import com.eternal.base.protocol.ProtocolTransformer;
import com.eternal.base.router.RouterActivityPath;
import com.eternal.framework.binding.command.BindingAction;
import com.eternal.framework.bus.Messenger;
import com.eternal.framework.bus.RxBus;
import com.eternal.framework.utils.KLog;
import com.eternal.framework.utils.Utils;
import com.eternal.notification.R;
import com.eternal.widget.guqiang.ProgressToolbar;

import io.reactivex.Completable;
import io.reactivex.CompletableEmitter;
import io.reactivex.CompletableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * @author Administrator
 */
@Route(path = RouterActivityPath.Notification.PAGE_ADD)
public class NotificationActivity extends AppCompatActivity {
    public static final String SHOW_DELETE_DIALOG="show notification delete dialog";
    public static final String SHOW_NAME_EXISTS_DIALOG="show notification name exists dialog";
    public static final String SHOW_NAME_EMPTY_DIALOG="show notification name empty dialog";
    private Disposable timeEvent,disConnEvent,nameRefresh;
    private ProgressToolbar toolbar;
    private String timeStr;
    private String mac;
    private byte port;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);
        Intent intent=getIntent();
        mac=intent.getStringExtra(ActivityEvent.DEVICE_MAC);
        port =intent.getByteExtra(ActivityEvent.DEVICE_PORT,(byte)0x0);
        initFragment(mac,port,intent.getByteExtra(ActivityEvent.NOTIFICATION_TYPE, (byte) 0),
                intent.getStringExtra(ActivityEvent.NOTIFICATION),
                intent.getBooleanExtra(ActivityEvent.DEVICE_DEGREE, true));
        initView(intent.getStringExtra(ActivityEvent.DEVICE_TIME));
        refreshName();
        registerMassage();
    }

    private void initFragment(String mac,byte port,byte type, String notification, boolean isDegree){
        Bundle bundle=new Bundle();
        bundle.putString(ActivityEvent.DEVICE_MAC, mac);
        bundle.putByte(ActivityEvent.DEVICE_PORT, port);
        bundle.putString(ActivityEvent.NOTIFICATION, notification);
        bundle.putBoolean(ActivityEvent.DEVICE_DEGREE, isDegree);
        Fragment content;
        if(type== BluetoothKey.AUTOMATION){
            content=new AutomationFragment();
            content.setArguments(bundle);
            ((ProgressToolbar) findViewById(R.id.toolbar))
                    .setTitle(getString(notification==null?R.string.title_add_automation:R.string.title_edit_automation));
        }else{
            bundle.putByte(ActivityEvent.NOTIFICATION_TYPE, type);
            content=new OtherFragment();
            content.setArguments(bundle);
            if(type==BluetoothKey.ALARMS){
                ((ProgressToolbar) findViewById(R.id.toolbar))
                        .setTitle(getString(notification==null?R.string.title_add_alarm:R.string.title_edit_alarm));
            }else{
                ((ProgressToolbar) findViewById(R.id.toolbar))
                        .setTitle(getString(notification==null?R.string.title_add_notification:R.string.title_edit_notification));
            }
        }
        FragmentTransaction transaction= getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.layout_content, content);
        transaction.commit();
    }

    private void initView(String time){
        toolbar=findViewById(R.id.toolbar);
        toolbar.getBack().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        if (RepositoryInjection.providerDeviceRepository().isConnect(mac)) {
            toolbar.setTimeColor(ContextCompat.getColor(this, android.R.color.white));
            toolbar.setTime(Utils.getString(R.string.tip_connect,
                    ProtocolTransformer.getTime(System.currentTimeMillis())));
            registerEvent();
        }else{
            toolbar.setTimeColor(ContextCompat.getColor(this, R.color.color_FF2D55));
            toolbar.setTime(RepositoryInjection.providerDeviceRepository().getTime(mac));
        }
    }

    private void registerEvent(){
        if (timeEvent == null || timeEvent.isDisposed()) {
            timeEvent= RxBus.getDefault()
                    .toObservable(Long.class)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long time) {
                            toolbar.setTime(Utils.getString(R.string.tip_connect,
                                    ProtocolTransformer.getTime(time)));
                        }
                    });
        }
        if (disConnEvent == null || disConnEvent.isDisposed()) {
            disConnEvent= RxBus.getDefault()
                    .toObservable(BluetoothEvent.class)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<BluetoothEvent>() {
                        @Override
                        public void accept(BluetoothEvent event) {
                            if(event.what== BluetoothEvent.DISCONNECT){
                                if(mac.equals(event.obj)){
                                    timeStr= Utils.getString(R.string.tip_last,
                                            ProtocolTransformer.getTime(System.currentTimeMillis()));
                                    Completable.create(new CompletableOnSubscribe() {
                                        @Override
                                        public void subscribe(CompletableEmitter emitter) throws Exception {
                                            toolbar.setTime(timeStr);
                                            toolbar.setTimeColor(ContextCompat.getColor(NotificationActivity.this, R.color.color_FF2D55));
                                        }
                                    }).subscribeOn(AndroidSchedulers.mainThread()).subscribe();
                                    timeEvent.dispose();
                                    timeEvent=null;
                                }
                            } else if (event.what == BluetoothEvent.CONNECT) {
                                if(mac.equals(event.obj)){
                                    timeStr = Utils.getString(R.string.tip_connect,
                                            ProtocolTransformer.getTime(System.currentTimeMillis()));
                                    toolbar.setTime(timeStr);
                                    toolbar.setTimeColor(ContextCompat.getColor(Utils.getContext(), android.R.color.white));
                                    registerEvent();
                                }
                            }
                        }
                    });
        }
    }

    @SuppressLint("CheckResult")
    private void refreshName() {
        if (nameRefresh == null || nameRefresh.isDisposed()) {
            nameRefresh = RepositoryInjection.providerDeviceRepository()
                    .getDeviceName(mac, port)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<DeviceName>() {
                        @Override
                        public void accept(DeviceName deviceName) {
                            if (deviceName != null) {
                                toolbar.setSubtitle(deviceName.name);
                            }
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) {
                            KLog.e(throwable);
                        }
                    });
        }
    }

    private void unregisterEvent(){
        if(timeEvent!=null){
            timeEvent.dispose();
            timeEvent=null;
        }
        if(disConnEvent!=null){
            disConnEvent.dispose();
            disConnEvent=null;
        }
    }

    private void registerMassage(){
        Messenger.getDefault().register(this, SHOW_NAME_EXISTS_DIALOG, new BindingAction() {
            @Override
            public void call() {
                showNameDialog("That name has already been taken.");
            }
        });
        Messenger.getDefault().register(this, SHOW_NAME_EMPTY_DIALOG, new BindingAction() {
            @Override
            public void call() {
                showNameDialog("The name cannot be empty.");
            }
        });
    }

    private void unregisterMassage(){
        Messenger.getDefault().unregister(this);
    }

    private void showNameDialog(String msg){
        KLog.e("show name dialog");
        View view=LayoutInflater.from(this).inflate(R.layout.dialog_tip_ok, null, false);
        TextView content=view.findViewById(R.id.tv_content);
        content.setText(msg);
        final MaterialDialog dialog= new MaterialDialog.Builder(this)
                .backgroundColor(0x00ffffff)
                .customView(view, false)
                .autoDismiss(true)
                .build();
        view.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        unregisterEvent();
        unregisterMassage();
        if (nameRefresh != null) {
            nameRefresh.dispose();
            nameRefresh = null;
        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        ARouter.getInstance().build(RouterActivityPath.Detail.PAGE_DETAIL)
                .withTransition(R.anim.left_in, R.anim.right_out)
                .navigation(this, new NavCallback() {
                    @Override
                    public void onArrival(Postcard postcard) {
                        finish();
                    }
                });
    }
}
